<?php

namespace App\Http\Controllers\Site\Custom\Purchaser;

use App\B2BProject\Area;
use App\B2BProject\Site\HelperControllerBuildTrait;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use App\B2BProject\Custom\Business\Address;

class AddressController extends Controller
{
    use HelperControllerBuildTrait;

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $request->query->set('page', $request->query('page', $request->page));
        $pageSize = $request->query('pageSize', $request->pageSize);

        if ($request->ajax()) {
            if ($id = $request->query('id')) {
                $address = Address::availableMember()->whereId($id)->firstOrFail();

                return response()->json([
                    'data' => [
                        'id'       => $id,
                        'name'     => $address->name,
                        'provid' => $address->province_id,
                        'cityid'     => $address->city_id,
                        'areaid'     => $address->county_id,
                        'addr'     => $address->detail_area,
                        'postnum'  => $address->code,
                        'tel'      => $address->tel_phone,
                    ],
                ]);
            }

            $addresses = Address::where('member_id', \Auth::id())->paginate($pageSize);

            $data = [
                'pagingConfData' => [
                    'page'     => $request->page,
                    'pageSize' => $pageSize,
                    'total'    => $addresses->total(),
                ],
            ];

            foreach ($addresses as $address) {
                $data['data'][] = [
                    'id'       => $address->id,
                    'name'     => $address->name,
                    'provname' => Area::getName($address->province_id),
                    'city'     => Area::getName($address->city_id),
                    'area'     => Area::getName($address->county_id),
                    'addr'     => $address->detail_area,
                    'postnum'  => $address->code,
                    'tel'      => $address->tel_phone,
                ];
            }

            return response()->json($data);
        }

        return view('host/custom/purchaser/address/index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('host/custom/purchaser/address/create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $member = \Auth::user();
        try {
            return \DB::transaction(function () use ($request, $member) {
                $validator = Validator::make($request->all(), [
                    'name'        => 'required', // 姓名
                    'detail_area' => 'required', // 详细地址
                    'code'        => 'required', // 邮编
                    'tel_phone'   => 'required', //手机
                    'province_id' => 'required|exists:areas,id,level,1', // 省份 ID
                    'city_id'     => 'required|exists:areas,id,level,2', // 城市 ID
                    'county_id'   => 'required|exists:areas,id,level,3', // 乡镇 ID
                ]);
                if ($validator->fails()) {
                    return redirect()->back();
                }

                $data = $request->only([
                    'name',
                    'detail_area',
                    'code',
                    'tel_phone',
                    'province_id',
                    'city_id',
                    'county_id',
                ]);

                $data['default'] = $request->input('default', 0);
                if ($data['default'] == 1) {
                    $member_id = $member->id;
                    $addresses = Address::where('member_id', $member_id)->update(['default' => 0]);
                }

                $address = Address::create($data);
                $member->address()->save($address);

                return redirect()->route('account.address.index');
            });

        } catch (ModelNotFoundException $e) {
            throw $e;
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        return view('host/custom/purchaser/address/edit');
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int                      $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $member = \Auth::user();
        try {
            return \DB::transaction(function () use ($request, $member, $id) {
                $validator = Validator::make($request->all(), [
                    'name'        => 'required', // 姓名
                    'detail_area' => 'required', // 详细地址
                    'code'        => 'required', // 邮编
                    'tel_phone'   => 'required', //手机
                    'province_id' => 'required|exists:areas,id,level,1', // 省份 ID
                    'city_id'     => 'required|exists:areas,id,level,2', // 城市 ID
                    'county_id'   => 'required|exists:areas,id,level,3', // 乡镇 ID
                ]);
                if ($validator->fails()) {
                    return redirect()->back();
                }
                $data            = $request->only([
                    'name',
                    'detail_area',
                    'code',
                    'tel_phone',
                    'province_id',
                    'city_id',
                    'county_id',
                ]);

                $data['default'] = $request->input('default', 0);

                if ($data['default'] == 1) {
                    $member_id = $member->id;
                    $addresses = Address::where('member_id', $member_id)->update(['default' => 0]);
                }

                $address = Address::AvailableMember()->whereId($id)->firstOrFail();
                $address->update($data);

                return redirect()->route('account.address.index');
            });

        } catch (ModelNotFoundException $e) {
            throw($e);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param Request $request
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request, $id = null)
    {
        if ($request->ajax()) {
            $id = $request->id;

            Address::AvailableMember()->findOrFail($id)->delete();

            return $this->index($request);
        }

    }
}
